<?php

namespace App\Jobs\Controller;

use App\Common\Libs\ArrayHelper;
use App\Consts\GlobalConst;
use App\Consts\GlobalCounterConst;
use App\Jobs\BaseJob;
use App\Models\UserCollect;

class PackageJob extends BaseJob
{
    /**
     * 修改收藏夹的内容总数
     * @param array $data ['user_id' => '', 'package_id' => '', 'trend' => '']
     * @return bool
     */
    public function changeTotal($data)
    {
        $data = $data['msgContent'];
        // 修改收藏夹内容总数<total>
        $collectPackage = repository()->PackageRepository->getCollectPackageByUserIdAndTargetId($data['user_id'], $data['package_id']);
        if ($collectPackage) {
            $total = $collectPackage->total + $data['trend'];
            $loadData = [
                'total' => $total,
            ];
            if ($data['trend'] != GlobalCounterConst::DECREASE) {
                $loadData = ArrayHelper::merge($loadData, [
                    'updated_at' => time(),
                ]);
            }
            repository()->PackageRepository->updateCollectPackage($collectPackage, $loadData);
        }

        return true;
    }

    public function delPackage($data)
    {
        $data = $data['msgContent'];

        $collects = UserCollect::getInstance($data['user_id'])
            ->where('user_id', $data['user_id'])
            ->where('is_deleted', GlobalConst::IS_NOT_DELETE)
            ->get();
        foreach ($collects as $collectModel) {
            service()->CollectService->cancelCollect([
                'user_id' => $data['user_id'],
                'package_id' => $data['package_id'],
                'target_id' => $collectModel->target_id,
                'target_type' => $collectModel->target_type
            ]);
        }

        return true;
    }
}
